<script lang="ts" setup>
import { ref, computed } from "vue";
import { ArrowLeft, ArrowRight } from "@element-plus/icons-vue";
import dayjs from "dayjs";

// Emit: 触发日期变更事件
const emit = defineEmits<{
  (event: "update:modelValue", value: string): void;
}>();

const currentYear = ref(null)
const currentMonth = ref(null)
// 当前日期
const currentDate = ref(new Date());

// 当前选择的日期，默认为当前月份
const selectedDate = ref(new Date());
currentMonth.value = selectedDate.value.getMonth()+1;
currentYear.value = selectedDate.value.getFullYear();
// 计算属性：是否禁用下一个月按钮（如果已是当月）
const isNextDisabled = computed(() => {
  const currentYear = currentDate.value.getFullYear();
  const currentMonth = currentDate.value.getMonth();
  const selectedYear = selectedDate.value.getFullYear();
  const selectedMonth = selectedDate.value.getMonth();
  return selectedYear >= currentYear && selectedMonth >= currentMonth;
});
// 方法：切换月份
const changeMonth = (direction: "prev" | "next" | 'now') => {
  const year = selectedDate.value.getFullYear();
  const month = selectedDate.value.getMonth();

  // 根据方向调整月份
  if (direction === "now") {
    selectedDate.value = new Date();
  } else if (direction === "prev") {
    selectedDate.value = new Date(year, month - 1, 1);
  } else if (direction === "next" && !isNextDisabled.value) {
    selectedDate.value = new Date(year, month + 1, 1);
  }


  currentYear.value = selectedDate.value.getFullYear();
  currentMonth.value = selectedDate.value.getMonth()+1;

  // 格式化日期并触发事件
  const formattedDate = dayjs(selectedDate.value).format('YYYY-MM-DD HH:mm:ss'); // 格式化为 "YYYY-MM"
  emit("update:modelValue", formattedDate);
};
</script>

<template>
  <el-button-group>
    <!-- 上一个月按钮 -->
    <el-button
        type="primary"
        :icon="ArrowLeft"
        @click="changeMonth('prev')"
    >
      上一个月
    </el-button>

   <el-button
       @click="changeMonth('now')" type="primary" > {{currentYear}}年{{currentMonth}}月</el-button>

    <!-- 下一个月按钮 -->
    <el-button
        type="primary"
        :disabled="isNextDisabled"
        @click="changeMonth('next')"
    >
      下一个月<el-icon class="el-icon--right"><ArrowRight /></el-icon>
    </el-button>
  </el-button-group>
</template>

<style scoped lang="scss">

</style>
